import { writeFile } from 'fs/promises'

//const DRAW_THINGS_URL = 'http://127.0.0.1:7860/sdapi/v1/txt2img'
const DRAW_THINGS_URL = 'http://127.0.0.1:7860/sdapi/v1/txt2img'
const BATCH_COUNT = 1
const IMG_SIZE_W = 512
const IMG_SIZE_H = 768
const MAX_FILE_NAME_LEN = 30

const prompt = 'solo,red background,1Girl,3boys, full body,squatting cowgirl position,complated nude, Dilated vagina, Dilated, vagina, spread legs,ruanyi0464,see-through,bottomless,pussy,best quality,masterpiece,highres,official art,extremely detailed cg unity 8k wallpaper'

const params = {
  model: 'realcartoonrealistic_v15_f16.ckpt',
  prompt,
  negative_prompt: 
    '<badhandv4>katana,holding sword,, (unhealthy-deformed-joints:2), (unhealthy-hands:2), easynegative, ng_deepnegative_v1_75t, (worst quality:2), (low quality:2),(normal quality:2), lowres, bad anatomy, badhandv4, ((extra limbs)), ((extra legs)), ((fused legs)), ((extra arms)), ((fused arms)), normal quality, ((monochrome)), ((grayscale)), ((watermark)), uneven eyes, lazy eye, (((mutated hand))),',
  //sampler: 'Euler Ancestral',
  seed: -1,
  steps: 30,
  guidance_scale: 4,
  batch_count: BATCH_COUNT,
  width: IMG_SIZE_W,
  height: IMG_SIZE_H
}

const optsy = {
  method: 'POST',
  mode: 'no-cors',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(params)
}

const now = Date.now()
const path = '/Users/david/Pictures/ai-output/'
const getFileName = (idx) => 
  `${prompt.replace(/\s/g, '_').substring(0, MAX_FILE_NAME_LEN).toLowerCase()}_${now}_${idx}.png`

const saveImg = async (data, idx) => {
  const fileName = getFileName(idx)
  await writeFile(path + fileName, data, 'base64')
}

const run = async () => {
  for (let i = 4; i < 11; i++) {
    console.log(i)
    params.guidance_scale = i
    const opts = {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(params)
    }
    console.log(opts.body)
    const res = await fetch(DRAW_THINGS_URL, opts)
    const data = await res.json()
    //console.log("data===" + data)
    //const images = data.images.map(saveImg)

    //await Promise.all(images)
  }
}

await run()

